import './globals.css';
import 'react-photo-view/dist/react-photo-view.css';
import clsx from 'clsx';
import localFont from 'next/font/local';
import { cookies } from 'next/headers';
import { Toaster } from 'react-hot-toast';
import { getRequestCookiesTheme } from 'src/utils';
import { JotaiProvider } from './components/JotaiProvider';
import { ThemeController } from './components/ThemeController';
import { getUser } from 'src/actions/user';
import { getStorageSystemList } from 'src/actions/storageSystem';
import { SyncUserAtom } from './components/SyncUserAtom';
import type { Metadata } from 'next';
import type { StorageSystemOption, User } from 'src/model';

const doto = localFont({
  src: './fonts/Doto-Regular.ttf',
  variable: '--font-doto',
  weight: '400', // 该字体文件中，只有 400 的 regular 字体
});

const zcool = localFont({
  src: './fonts/ZCOOLXiaoWei-Regular.ttf',
  variable: '--font-zcool',
  weight: '400',
});

export const metadata: Metadata = {
  title: '星恒云图',
  description: '响应式的图像处理和分析平台，支持图像和视频上传、存储、优化和内容分发网络 (CDN)',
  keywords: ['星恒云图', '响应式图像处理平台', '图像处理', '图像存储', '内容分发网络', 'CDN'],
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const cookiesStore = await cookies();
  const defaultTheme = getRequestCookiesTheme(cookiesStore);

  let defaultUser: User | undefined = undefined;
  const user = await getUser();
  if (user) {
    defaultUser = {
      id: user.id,
      name: user.name,
      email: user.email,
      avatar: user.avatar || '',
      phone: user.phone || '',
      bio: user.bio || '',
      role: user.role,
      isActive: user.isActive,
      isVerified: user.isVerified,
    };
  }

  let defaultStorageSystemOptions: StorageSystemOption[] | undefined = undefined;
  if (user?.id) {
    const storageSystemList = await getStorageSystemList(user?.id);
    defaultStorageSystemOptions = storageSystemList.map((item) => ({
      label: item.name,
      value: item.id,
      isPublic: item.isPublic,
      disabled: !item.isActive,
      description: item.description,
    }));
  }

  return (
    <JotaiProvider
      initialValues={{
        appTheme: defaultTheme,
        user: defaultUser,
        storageSystemOptions: defaultStorageSystemOptions,
      }}
    >
      <SyncUserAtom initialValue={defaultUser} />
      <html lang="zh-CN" data-theme={defaultTheme}>
        <body className={clsx(doto.variable, zcool.variable, 'antialiased')}>{children}</body>
      </html>
      <ThemeController isListener />
      <Toaster
        position="top-center"
        reverseOrder={false}
        gutter={8}
        toastOptions={{
          duration: 3000,
          removeDelay: 1000,
        }}
      />
    </JotaiProvider>
  );
}
